package Listeners;

import DAO.DbDao;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;

/**
 * Created by hadoop on 17-6-14.
 * Listener类，在应用启动时向ServletContext添加通用的 DAO 类用于数据库链接
 * 这种方式性能很差，最好使用连接池实现
 */
@WebListener
public class GetConnListener implements ServletContextListener{

    @Override
    public void contextInitialized(ServletContextEvent servletContextEvent) {
        ServletContext application = servletContextEvent.getServletContext();
        String driver = application.getInitParameter("sqlDriver");
        String url = application.getInitParameter("sqlUrl");
        String user = application.getInitParameter("sqlUser");
        String pass = application.getInitParameter("sqlPass");

        DbDao dao = new DbDao(driver,url,user,pass);
        application.setAttribute("DbDao",dao);
    }

    @Override
    public void contextDestroyed(ServletContextEvent servletContextEvent) {
        DbDao dao = (DbDao) servletContextEvent.getServletContext().getAttribute("DbDao");
        try {
            dao.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
